package com.bjtech.web.action.management;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi2.hssf.usermodel.HSSFCell;
import org.apache.poi2.hssf.usermodel.HSSFDateUtil;
import org.apache.poi2.hssf.usermodel.HSSFRow;
import org.apache.poi2.hssf.usermodel.HSSFSheet;
import org.apache.poi2.hssf.usermodel.HSSFWorkbook;
import org.apache.poi2.poifs.filesystem.POIFSFileSystem;
import org.ssi.web.struts.bean.UploadFile;

import com.bjtech.bo.RoomImportDataBO;
import com.bjtech.dao.AssignMeterInfoDao;
import com.bjtech.dao.BaseBuildingInfoDao;
import com.bjtech.dao.BaseRoomInfoDao;
import com.bjtech.dao.LoginUserInfoDao;
import com.bjtech.dao.SinkInfoDao;
import com.bjtech.dao.SysAccessaryDao;
import com.bjtech.domain.AssignMeterInfo;
import com.bjtech.domain.BaseBuildingInfo;
import com.bjtech.domain.BaseRoomInfo;
import com.bjtech.domain.BaseUnitInfo;
import com.bjtech.domain.LoginUserInfo;
import com.bjtech.domain.SinkInfo;
import com.bjtech.domain.SysAccessary;
import com.bjtech.domain.query.BaseBuildingInfoQuerySpec;
import com.bjtech.domain.query.BaseRoomInfoQuerySpec;
import com.bjtech.web.action.LyheatBaseAction;

public class BaseRoomInfoAction extends LyheatBaseAction {

	private static final long serialVersionUID = 1L;
	private BaseRoomInfoDao baseRoomInfoDao;
	private BaseBuildingInfoDao baseBuildingInfoDao;
	private LoginUserInfoDao loginUserInfoDao;

	private BaseRoomInfoQuerySpec selectBean;

	private List buidList;
	private List assignMeterList;
	private AssignMeterInfoDao assignMeterInfoDao;

	private List sinkList;
	private SinkInfoDao sinkInfoDao;

	private String custom;
	private SysAccessaryDao sysAccessaryDao;

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	private static DecimalFormat df = new DecimalFormat("#");
	public void prepare() throws Exception {

	}

	public BaseRoomInfoAction() throws Exception {
		model = new BaseRoomInfo();
		selectBean = new BaseRoomInfoQuerySpec();
	}

	public void setBaseRoomInfoDao(BaseRoomInfoDao baseRoomInfoDao) {
		this.baseRoomInfoDao = baseRoomInfoDao;
	}

	public String execute() {
		return this.list();
	}

	public String list() {
		buidList = baseBuildingInfoDao.selectEntityList(new BaseBuildingInfo(),
				new BaseBuildingInfoQuerySpec());
		selectBean.queryParamString();
		list = this.baseRoomInfoDao.selectEntityPaginatedList(
				new BaseRoomInfo(), selectBean);
		return "list";
	}

	public String add() {
		buidList = baseBuildingInfoDao.selectEntityList(new BaseBuildingInfo(),
				new BaseBuildingInfoQuerySpec());
		return "edit";
	}

	public String save() {
		BaseRoomInfo entity = (BaseRoomInfo) model;
		if (entity.getId() == null) {
			Long roomId = baseRoomInfoDao.insertEntity(entity);
			
			//自动生成登陆用户
			LoginUserInfo loginUser = new LoginUserInfo();
			loginUser.setUser_name(entity.getName()+entity.getHouse_num());
			loginUser.setPass_word("123456");
			loginUser.setUser_role(7l);
			loginUser.setRoom_id(roomId);
			loginUser.setProj_id(entity.getProj_id());
			loginUser.setBuild_id(entity.getBuild_id());
			loginUser.setShare_area_id(entity.getArea_id());
			loginUser.setReal_name(entity.getName());
			loginUserInfoDao.insertEntity(loginUser);
		} else {
			baseRoomInfoDao.updateEntity(entity);
		}
		return "success";
	}

	public String edit() {
		buidList = baseBuildingInfoDao.selectEntityList(new BaseBuildingInfo(),
				new BaseBuildingInfoQuerySpec());
		model = this.baseRoomInfoDao.selectEntity(new BaseRoomInfo(), id);
		return "edit";
	}

	public String view() {
		model = this.baseRoomInfoDao.selectEntity(new BaseRoomInfo(), id);
		assignMeterList = this.assignMeterInfoDao
				.selectAssignMeterListByRoomId(id);
		sinkList = this.sinkInfoDao.selectSinkListByRoomId(id);
		return "view";
	}
	
	public String viewByAssignNumber() {
		String serious_num= super.getRequest().getParameter("serious_num");
		model = this.baseRoomInfoDao.selectBaseRoomInfoByAssignMeterNum(serious_num);
		Long roomId= ((BaseRoomInfo)model).getId();
		assignMeterList = this.assignMeterInfoDao
				.selectAssignMeterListByRoomId(roomId);
		sinkList = this.sinkInfoDao.selectSinkListByRoomId(roomId);
		return "view";
	}

	public String delete() {
		//级联删除
		this.baseRoomInfoDao.deleteRoomLinkedObjs(id);
		model = this.baseRoomInfoDao.deleteEntity(new BaseRoomInfo(), id);
		return "success";
	}

	public String uploadMF() {
		custom = "BaseRoomInfo/upload.jsp";
		return "custom";
	}

	public String uploadRoomFile() {
		SysAccessary sysAccessary = new SysAccessary();

		for (UploadFile uploadFile : getUploadFileList()) {
			sysAccessary = new SysAccessary();
			sysAccessary.setLink_id(null);
			// sysAccessary.setLink_tab("AssignMeterFile");
			sysAccessary.setAc_sname(uploadFile.getFileName());
			sysAccessary.setUrl(uploadFile.getFileSavePath());
			this.sysAccessaryDao.insertEntity(sysAccessary);
		}

		// 读取上传文件
		List<RoomImportDataBO> records = readUploadFileData(getUploadFileList().get(0)
				.getFileSavePath());
		// 将数据导入数据库
		String result = this.baseRoomInfoDao.insertUploadRoomInfos(records);
		
		if(result!=null){
			if("".equals(result)){
				super.renderJavaScript("window.onload=function(){alert('数据导入完成！');location.href='BaseRoomInfo!list.action';}");
			}else{
				super.renderJavaScript("window.onload=function(){alert('"+result+"');history.back();}");
			}
		}
		return null;
		//return "success";
	}

	private List<RoomImportDataBO> readUploadFileData(String fileSavePath) {
		List<RoomImportDataBO> importRoomList = new ArrayList<RoomImportDataBO>();
		StringBuffer sb = new StringBuffer();
		String ctxDir = getRequest().getSession().getServletContext()
				.getRealPath(String.valueOf(File.separatorChar));

		if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
			ctxDir = ctxDir + File.separatorChar;
		}
		try {
			FileInputStream fis = new FileInputStream(ctxDir + fileSavePath);
			POIFSFileSystem pfs = new POIFSFileSystem(fis);
			HSSFWorkbook hwb = new HSSFWorkbook(pfs);
			HSSFSheet sheet = hwb.getSheetAt(0);
			int rowNum = sheet.getLastRowNum();
			String last_id_cell_value="";
			RoomImportDataBO cur_data = new RoomImportDataBO();
			for (int i = 1; i <= rowNum; i++) {
				HSSFRow row = sheet.getRow(i);
				int colNum = row.getPhysicalNumberOfCells();
				if (row != null && colNum == 37) {
					String cur_id_cell_value = getStringCellValue(row.getCell((short)0));
					if(!"".equals(cur_id_cell_value)&&cur_id_cell_value!=null){
						if("".equals(last_id_cell_value)){
							cur_data = new RoomImportDataBO();
						}
						else if(!last_id_cell_value.equals(cur_id_cell_value)){
							importRoomList.add(cur_data);
							cur_data = new RoomImportDataBO();
						}
						cur_data = readDataFromRow(row,cur_data);
						last_id_cell_value = cur_id_cell_value;
					}
				}
			}
			if(rowNum>=2){
				importRoomList.add(cur_data);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return importRoomList;
	}

	/**
	 * 
	 * @param row
	 * @param id_cell_value用户识别是RoomInfo是否发生改变
	 * @return
	 */
	/**
	 **[0]*1.0*[1]*康爱文*[2]*1.393055921E10*[3]**[4]*1.0*[5]*1.0*[6]*101.0*
	 *[7]*参与*[8]*61.33*[9]*46.0*[10]*卧室*[11]*0909020788123*
	 *[12]*XYE-R*[13]*01*[14]*01 *[15]*813.0*[16]*无*[17]*10.0*
	 *[18]*760.0*[19]*140.0*[20]*60.0*[21]*640.0*[22]*温控阀*[23]*有*
	 *[24]*待定*[25]*622.972*[26]*1.0*[27]*1.0*[28]*刘翔*[29]*刘翔*[30]*2012/03/15*[31]*无备注
	 **[32]*户修正系统*[33]*散热编号*[34]*散热器是否参与分摊**[35]*楼层位置*[36]*是否为边户*
	 */
	private RoomImportDataBO readDataFromRow(HSSFRow row,RoomImportDataBO roomInfodata) {
		BaseRoomInfo room = new BaseRoomInfo();
		SinkInfo sink = new SinkInfo();
		AssignMeterInfo meter = new AssignMeterInfo();
		BaseUnitInfo unit = new BaseUnitInfo();
		
		roomInfodata.setBuild_no(getStringCellValue(row.getCell((short) 3)));
		
		unit.setUnit_name(Long.valueOf(getStringCellValue(row.getCell((short) 5))));
		
		if(roomInfodata.getBaseRoomInfo()!=null&&roomInfodata.getBaseRoomInfo().getHouse_num()!=null&&!"".equals(roomInfodata.getBaseRoomInfo().getHouse_num())){
		}else{
			room.setName(getStringCellValue(row.getCell((short) 1)));
			room.setTel(getStringCellValue(row.getCell((short) 2)));
			room.setFloor_no(Long.valueOf(getStringCellValue(row.getCell((short) 4))));
			room.setHouse_num(getStringCellValue(row.getCell((short) 6)));
			if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)7)))){
				if(getStringCellValue(row.getCell((short)7)).equals("参与")){
					room.setIs_cal(0l);
				}else if(getStringCellValue(row.getCell((short)7)).equals("不参与")){
					room.setIs_cal(1l);
				}
			}
			if(getStringCellValue(row.getCell((short)8))!=null&&!"".equals(getStringCellValue(row.getCell((short)8)))){
				room.setStruct_area(new BigDecimal(getStringCellValue(row.getCell((short)8))).setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			if(getStringCellValue(row.getCell((short)9))!=null&&!"".equals(getStringCellValue(row.getCell((short)9)))){
				room.setHear_area(new BigDecimal(getStringCellValue(row.getCell((short)9))).setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			if(getStringCellValue(row.getCell((short)32))!=null&&!"".equals(getStringCellValue(row.getCell((short)32)))){
				room.setXz_factor(new BigDecimal(getStringCellValue(row.getCell((short)32))));
			}
			if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)35)))){
				if(getStringCellValue(row.getCell((short)35)).equals("顶楼")){
					room.setFloor_pos(1l);
				}else if(getStringCellValue(row.getCell((short)35)).equals("中间层")){
					room.setFloor_pos(2l);
				}else if(getStringCellValue(row.getCell((short)35)).equals("底层")){
					room.setFloor_pos(3l);
				}
			}
			if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)36)))){
				if(getStringCellValue(row.getCell((short)36)).equals("是边户")){
					room.setIs_side(0l);
				}else if(getStringCellValue(row.getCell((short)36)).equals("不是边户")){
					room.setIs_side(1l);
				}
			}
			roomInfodata.setBaseRoomInfo(room);
		}
		meter.setSerious_num(getStringCellValue(row.getCell((short)11)));
		meter.setModel(getStringCellValue(row.getCell((short)12)));
		meter.setSoft_version(getStringCellValue(row.getCell((short)13)));
		meter.setHard_version(getStringCellValue(row.getCell((short)14)));
		meter.setInstall_man(getStringCellValue(row.getCell((short)28)));
		meter.setRecord_man(getStringCellValue(row.getCell((short)29)));
		try {
			meter.setInstall_date(sdf.parse((getStringCellValue(row.getCell((short)30)))));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		meter.setDemo(getStringCellValue(row.getCell((short)31)));
		
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)10)))){
			if(getStringCellValue(row.getCell((short)10)).trim().equals("客厅")){
				sink.setHouse_function(1l);
			}
			else if(getStringCellValue(row.getCell((short)10)).trim().equals("卧室")){
				sink.setHouse_function(2l);
			}
			else if(getStringCellValue(row.getCell((short)10)).trim().equals("厨房")){
				sink.setHouse_function(3l);
			}
			else if(getStringCellValue(row.getCell((short)10)).trim().equals("卫生间")){
				sink.setHouse_function(4l);
			}
			else{
				sink.setHouse_function(5l);
			}
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)15)))){
			if(getStringCellValue(row.getCell((short)15)).equals("813")){
				sink.setType(1l);
			}
			else{
				sink.setType(2l);
			}
		}
		sink.setBrand(getStringCellValue(row.getCell((short)16)));
		if(getStringCellValue(row.getCell((short)17))!=null&&!"".equals(getStringCellValue(row.getCell((short)17)))){
			sink.setPiece_num(new Long(getStringCellValue(row.getCell((short)17))));
		}
		if(getStringCellValue(row.getCell((short)18))!=null&&!"".equals(getStringCellValue(row.getCell((short)18)))){
			sink.setSink_height(new BigDecimal(getStringCellValue(row.getCell((short)18))));
		}
		if(getStringCellValue(row.getCell((short)19))!=null&&!"".equals(getStringCellValue(row.getCell((short)19)))){
			sink.setSink_width(new BigDecimal(getStringCellValue(row.getCell((short)19))));
		}
		if(getStringCellValue(row.getCell((short)20))!=null&&!"".equals(getStringCellValue(row.getCell((short)20)))){
			sink.setSink_length(new BigDecimal(getStringCellValue(row.getCell((short)20))));
		}
		if(getStringCellValue(row.getCell((short)21))!=null&&!"".equals(getStringCellValue(row.getCell((short)21)))){
			sink.setSink_cen_dis(new BigDecimal(getStringCellValue(row.getCell((short)21))));
		}
		
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)22)))){
			if(getStringCellValue(row.getCell((short)22)).trim().equals("有")){
				sink.setTemp_control(1l);
			}
			else if(getStringCellValue(row.getCell((short)22)).trim().equals("无")){
				sink.setTemp_control(2l);
			}
			else{
				sink.setTemp_control(2l);//默认为“无”
			}
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)23)))){
			if(getStringCellValue(row.getCell((short)23)).trim().equals("有")){
				sink.setHas_cover(0l);
			}
			else{
				sink.setHas_cover(1l);
			}
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)25)))){
			sink.setCal_power(new BigDecimal(getStringCellValue(row.getCell((short)25))));
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)26)))){
			sink.setCouple_factor(new BigDecimal(getStringCellValue(row.getCell((short)26))));
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)27)))){
			sink.setOther_factor(new BigDecimal(getStringCellValue(row.getCell((short)27))));
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)33)))){
			sink.setSink_no(new Long(getStringCellValue(row.getCell((short)33))));
		}
		if(StringUtils.isNotBlank(getStringCellValue(row.getCell((short)34)))){
			if(getStringCellValue(row.getCell((short)34)).equals("参与")){
				sink.setJoin_ft(0l);
			}else if(getStringCellValue(row.getCell((short)34)).equals("不参与")){
				sink.setJoin_ft(1l);
			}
		}
		
		roomInfodata.setBaseUnitInfo(unit);
		roomInfodata.getAssignMeterList().add(meter);
		roomInfodata.getSinkInfoList().add(sink);
		return roomInfodata;
	}

	private String getStringCellValue(HSSFCell cell) {// 获取单元格数据内容为字符串类型的数据
		String strCell = "";
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			strCell = cell.getStringCellValue().trim();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
		case HSSFCell.CELL_TYPE_FORMULA:
			if(HSSFDateUtil.isCellDateFormatted(cell)){
				strCell = sdf.format(cell.getDateCellValue());
			}else{
				strCell = String.valueOf(cell.getNumericCellValue());
			}
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
		if (cell == null) {
			return "";
		}
		if(strCell.indexOf(".")!=-1&&(strCell.endsWith(".0")||strCell.endsWith(".00"))){
			strCell = strCell.substring(0,strCell.indexOf("."));
		}
		return strCell;
	}

	public BaseRoomInfoQuerySpec getSelectBean() {
		return selectBean;
	}

	public void setSelectBean(BaseRoomInfoQuerySpec selectBean) {
		this.selectBean = selectBean;
	}

	public BaseBuildingInfoDao getBaseBuildingInfoDao() {
		return baseBuildingInfoDao;
	}

	public void setBaseBuildingInfoDao(BaseBuildingInfoDao baseBuildingInfoDao) {
		this.baseBuildingInfoDao = baseBuildingInfoDao;
	}

	public List getBuidList() {
		return buidList;
	}

	public void setBuidList(List buidList) {
		this.buidList = buidList;
	}

	public BaseRoomInfoDao getBaseRoomInfoDao() {
		return baseRoomInfoDao;
	}

	public List getAssignMeterList() {
		return assignMeterList;
	}

	public void setAssignMeterList(List assignMeterList) {
		this.assignMeterList = assignMeterList;
	}

	public AssignMeterInfoDao getAssignMeterInfoDao() {
		return assignMeterInfoDao;
	}

	public void setAssignMeterInfoDao(AssignMeterInfoDao assignMeterInfoDao) {
		this.assignMeterInfoDao = assignMeterInfoDao;
	}

	public List getSinkList() {
		return sinkList;
	}

	public void setSinkList(List sinkList) {
		this.sinkList = sinkList;
	}

	public SinkInfoDao getSinkInfoDao() {
		return sinkInfoDao;
	}

	public void setSinkInfoDao(SinkInfoDao sinkInfoDao) {
		this.sinkInfoDao = sinkInfoDao;
	}

	public String getCustom() {
		return custom;
	}

	public void setCustom(String custom) {
		this.custom = custom;
	}

	public SysAccessaryDao getSysAccessaryDao() {
		return sysAccessaryDao;
	}

	public void setSysAccessaryDao(SysAccessaryDao sysAccessaryDao) {
		this.sysAccessaryDao = sysAccessaryDao;
	}

	public LoginUserInfoDao getLoginUserInfoDao() {
		return loginUserInfoDao;
	}

	public void setLoginUserInfoDao(LoginUserInfoDao loginUserInfoDao) {
		this.loginUserInfoDao = loginUserInfoDao;
	}
}
